package com.techwells.taco.utils;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.techwells.taco.networkservice.ServiceMediator;
import com.techwells.taco.networkservice.ServiceResponse;


@SuppressLint({ "HandlerLeak", "DefaultLocale" })
public class UpdateUtil {
	private int drawabledIconId;
	private Activity mainActivity;
	private Notification mNotification;
	private File mfile;
	private int lastProgress;
	public static UpdateUtil update;
	private Boolean isApkDownloading = false;
	public Handler downloadHandler = null;

	public Activity getActivity() {
		return mainActivity;
	}

	public UpdateUtil() {
		downloadHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case ServiceMediator.Service_Return_Success:
					ServiceResponse<?> response = (ServiceResponse<?>) msg.obj;
					if (null != response.getResponse()) {
						finishedDownloadApk((File) response.getResponse());
					}
					break;
				default:
					ServiceResponse<?> errorResp = (ServiceResponse<?>) msg.obj;
					if (null != errorResp.getReturnDesc()) {
						validationVersionFailed((String) errorResp
								.getReturnDesc());
					}
					finishedDownloadApk(null);
					break;
				}
			}
		};
	}

	public void validationVersionFailed(String errDesc) {
		ToastUtils.show(getActivity(), errDesc);
	}

	public void setDrawabledIconId(int drawId) {
		drawabledIconId = drawId;
	}

	public void initUpdateUtil(Activity act) {
		mainActivity = act;
		mNotificationManager = (NotificationManager) mainActivity
				.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public Boolean isUpdating() {
		return isApkDownloading;
	}

	public void setIsUpdating(Boolean updating) {
		isApkDownloading = updating;
	}

	private AlertDialog versionUpdateDialog;
	private NotificationManager mNotificationManager;

	public AlertDialog getVersionUpdateDialog() {
		return versionUpdateDialog;
	}

	public void setFile(File file) {
		mfile = file;
	}

	public void setVersionUpdateDialog(String title, String confirmString,
			String secondString, Activity context) {
		versionUpdateDialog = alertDialog(title, confirmString, secondString,
				context);
	}

	private void install(Context ctx) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(mfile),
					"application/vnd.android.package-archive");
			ctx.startActivity(intent);
		} catch (Exception e) {

		}
	}

	@SuppressWarnings("deprecation")
	public void showNotification() {
		isApkDownloading = true;
		lastProgress = 0;
		mNotification = new Notification(drawabledIconId, "下载更新包",
				System.currentTimeMillis());
		mNotification.setLatestEventInfo(mainActivity, "更新", "正在下载更新...1%",
				makeMoodIntent(drawabledIconId));
		mNotificationManager.notify(0, mNotification);
	}

	private PendingIntent makeMoodIntent(int moodId) {
		PendingIntent contentIntent = PendingIntent.getActivity(mainActivity,
				0, new Intent(mainActivity, mainActivity.getClass()).putExtra(
						"moodimg", moodId), PendingIntent.FLAG_UPDATE_CURRENT);
		return contentIntent;
	}

	public AlertDialog getVersionUpdateAlertDialog() {
		return versionUpdateDialog;
	}

	@SuppressWarnings("deprecation")
	public void finishedDownloadApk(File file) {
		isApkDownloading = false;

		if (null != file) {
			setFile(file);
			mNotification.setLatestEventInfo(mainActivity, "更新", "下载更新包完成。",
					makeMoodIntent(drawabledIconId));
			mNotificationManager.notify(0, mNotification);
			install(mainActivity);
			mNotificationManager.cancel(0);
		} else {
			mNotification.setLatestEventInfo(mainActivity, "更新", "下载更新包失败",
					makeMoodIntent(drawabledIconId));
			mNotificationManager.notify(0, mNotification);
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("DefaultLocale")
	public void downloadProgress(float progress) {
		progress = progress < 0 ? 0 : progress;
		progress = progress > 1 ? 1 : progress;
		int pro = (int) (progress * 100);
		if (pro - lastProgress > 1) {
			lastProgress = pro;
			String str = String.format("正在下载更新...%d%%", pro);
			mNotification.setLatestEventInfo(mainActivity, "更新", str,
					makeMoodIntent(drawabledIconId));
			mNotificationManager.notify(0, mNotification);
		}
	}

	public AlertDialog alertDialog(String title, String confirmString,
			String secondString, final Activity context) {
		return null;
	}

	public Handler getHandler() {
		return downloadHandler;
	}

	/**
	 * 异步下载apk包
	 * @param url
	 * @param context
	 */
	public void downloadApkFile(final String url,final Context context) {
		// 异步完成任务
		showNotification();
		new Thread(new Runnable() {
			public void run() {
				ServiceResponse<?> response = ServiceMediator.downloadAPK(url, UpdateUtil.this, context);
				Message message = new Message();
				message.what = response.getReturnCode();
				message.obj = response;
				getHandler().sendMessage(message);
			}
		}).start();
	}

	/** 版本升级路径 */
	public static String getUpdatePath(Context context) {
		String path = "/update.apk";
		path = context.getFilesDir().getAbsolutePath()
				+ path;
		return path;
	}
}